package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.DataUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import rx.subjects.PublishSubject;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;




    @Override
    public void computeHotArticle() {
        //查出5天的热点文章
        //查询五天的  (已上架  未删除)  的文章数据
        //               查询时间             5天                              时间格式
        String data = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyy-MM-dd 00:00:00"));

        //调用方法 查询符合时间的文章
        List<ApArticle> apArticleList = apArticleMapper.selectArticleByDate(data);

        //计算每篇文章的热点值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(apArticleList);


        //为每个频道缓存热点达到前三十的文章
        cacheTagToRedis(hotArticleVoList);

    }




    /**
     * 为每个频道缓存热度前三十的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //查询所有频道
        ResponseResult<List<AdChannel>> adChannelListResult = adminFeign.findAll();
        //判断远程调用结果
        if (adChannelListResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取所有频道
        List<AdChannel> adChannelList = adChannelListResult.getData();
        //遍历所有的频道
        for (AdChannel channel : adChannelList) {
            //获取文章和其对应的频道   频道id对应的 文章集合
            //频道所对应的文章集合  单个频道对应的文章集合
            List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                    //过滤当前频道的数据
                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(channel.getId()))
                    .collect(Collectors.toList());
            //调用方法  给热点文章排序
            //      单个频道对应的所有集合                 固定的前缀                             频道id
            sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());
        }
        //给推荐频道缓存三十条数数据
        //所有热点文章   key = 固定前缀 + __all__
        sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    /**
     *  给热点文章排序
     * @param hotArticleVos
     * @param cacheKey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
                                                    //根据分数倒序
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)   //30条
                .collect(Collectors.toList());   //返回集合

        //redis添加                      固定前缀+频道id             每个频道前三十条热点文章
        stringRedisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));

    }


    /**
     * 计算文章的分值 并且封装成vo对象
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
        //使用stream流
        return apArticleList.stream().map(apArticle -> {
            //创建封装的vo对象
            HotArticleVo hotArticleVo = new HotArticleVo();
            //拷贝属性
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            //计算文章分值算法
            Integer score = computeScore(apArticle);
            //设置分数
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算分值的方法
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        //点赞  * 3
        if (apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //阅读 * 1
        if (apArticle.getViews() != null){
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }

        //收藏 * 8
        if (apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        //评论 * 5
        if (apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //返回结果
        return score;
    }






    /**
     *
     * @param mess
     */
    @Override
    public void updateApArticle(AggBehaviorDTO mess) {
        //查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 修改文章的行为数据
        //判断查询出来的数据行为是否为null
        //如果为null 取 传递过来的聚合对象的值  如果不为null 则俩值相加
        if (mess.getView() != 0){
           int view =  (int)(apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
           apArticle.setViews(view);
        }
        if (mess.getLike() != 0){
            int view =  (int)(apArticle.getLikes() == null ? mess.getLike() : mess.getView() + apArticle.getLikes());
            apArticle.setViews(view);
        }
        if (mess.getComment() != 0){
            int view =  (int)(apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setViews(view);
        }
        if (mess.getCollect() != 0){
            int view =  (int)(apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setViews(view);
        }
        //修改修改之后为文章对象
        apArticleMapper.updateById(apArticle);


        //计算文章分值
        Integer score = computeScore(apArticle);
        //判断是否是今天的文章 如果是 分数 * 3
        String articleTime = DateUtils.dateToString(apArticle.getPublishTime());
        String newTime = DateUtils.dateToDateTime(new Date());
        if (articleTime.equals(newTime)){
            score *= 3;
        }

        //更新频道的缓存数据
        updateArticleCache(apArticle,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //更新推荐的缓存数据
        updateArticleCache(apArticle,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    /**
     * 更新文章缓存数据
     * @param apArticle
     * @param score
     * @param cacheKey
     */
    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        boolean flag = false;
        //根据key获取对应的文章的数据
        String hotArticleListJson = stringRedisTemplate.opsForValue().get(cacheKey);
        //文章数据不为null
        if (StringUtils.isNotBlank(hotArticleListJson)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleListJson, HotArticleVo.class);
            //如果文章列表中有当前文章  更新分数
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getAuthorId().equals(apArticle.getAuthorId())){
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }

            //缓存中没有对应的id
            if (!flag){
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hotArticleVo);
                hotArticleVo.setScore(score);
                hotArticleVoList.add(hotArticleVo);
            }
            //将热点文章集合 降序 30条 存入redis
            hotArticleVoList = hotArticleVoList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());

            stringRedisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
        }
    }
}












